package com.example.ex3;

import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;

public class RateActivity extends AppCompatActivity implements Runnable{

    private static final String TAG = "Rate";
    private float dollarRate;
    private float euroRate;
    private float wonRate;
    Handler handler;
    TextView result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rate);
        result=findViewById(R.id.result);

        SharedPreferences sharedPreferences = getSharedPreferences("myrate", Activity.MODE_PRIVATE);
        dollarRate = sharedPreferences.getFloat("dollar_rate",0.1577f);
        euroRate = sharedPreferences.getFloat("euro_rate",0.1420f);
        wonRate = sharedPreferences.getFloat("won_rate",191.3934f);

        Log.i(TAG,"onCreate:get from sp dollarRate="+dollarRate);
        Log.i(TAG,"onCreate:get from sp dollarRate="+euroRate);
        Log.i(TAG,"onCreate:get from sp dollarRate="+wonRate);

        Thread t = new Thread(this);
        t.start();
        SharedPreferences sp = this.getSharedPreferences("rate", MODE_PRIVATE);

        handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                if(msg.what==7){
                    Bundle bundle = (Bundle)msg.obj;
                    String lasttime = sp.getString("time","0000-00-00");
                    String time = bundle.get("time").toString().substring(12,22);
                    Log.i(TAG,"更新时间"+lasttime+"此次时间"+time);
                    if(!time.equals(lasttime)) {
                        SharedPreferences.Editor editor = sp.edit();
                        dollarRate = bundle.getFloat("web_dollar");
                        euroRate = bundle.getFloat("web_euro");
                        wonRate = bundle.getFloat("web_won");
                        result.setText("updated"+time);
                        editor.putString("time",time);
                        editor.apply();
                    }else{
                        Log.i(TAG,"同一天，已更新");
                    }
                }
                super.handleMessage(msg);
            }
        };

        //Intent intent2 = getIntent();
        //dollarRate = intent2.getFloatExtra("dollar_key",0.1577f);
        //euroRate = intent2.getFloatExtra("euro_key",0.1420f);
        //wonRate = intent2.getFloatExtra("won_key",191.3934f);

        //Log.i(TAG,"onCreate:dollar2="+dollarRate);
        //Log.i(TAG,"onCreate:euro2="+euroRate);
        //Log.i(TAG,"onCreate:won2="+wonRate);
    }
    public void change(View btn){
        Log.i(TAG,"click:11");
        EditText input = findViewById(R.id.rmb);
        String s = input.getText().toString();
        if(s.length()==0){
            Toast.makeText(this, "请输入数据", Toast.LENGTH_SHORT).show();
            return;
        }
        Log.i(TAG,"click:22");
        float inp = Float.parseFloat(s);
        float r = 0.0f;
        if(btn.getId()==R.id.dollar){
            r=inp * dollarRate;
        }else if(btn.getId()==R.id.euro){
            r=inp * euroRate;
        }else{
            r=inp * wonRate;
        }
        //result=findViewById(R.id.result);
        result.setText(String.valueOf(r));
    }
    public void open(View btn){
        Log.i(TAG,"open:33");
        openconfig();

    }

    private void openconfig() {
        Intent intent = new Intent(this,ConfigActivity.class);

        intent.putExtra("dollar_key",dollarRate);
        Log.i(TAG,"open:dollar"+dollarRate);
        intent.putExtra("euro_key",euroRate);
        Log.i(TAG,"open:euro"+euroRate);
        intent.putExtra("won_key",wonRate);
        Log.i(TAG,"open:won"+wonRate);

        //    startActivity(intent);
        startActivityForResult(intent,3);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(requestCode==3&&resultCode==6){
            Bundle bld = data.getExtras();
            dollarRate = bld.getFloat("dollar_key");
            euroRate = bld.getFloat("euro_key");
            wonRate = bld.getFloat("won_key");
            Log.i(TAG,"onActivityResult:dollarRate="+dollarRate);
            Log.i(TAG,"onActivityResult:euroRate="+euroRate);
            Log.i(TAG,"onActivityResult:wonRate="+wonRate);

            SharedPreferences sharedPreferences = getSharedPreferences("myrate",Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putFloat("dollar_rate",dollarRate);
            editor.putFloat("euro_rate",euroRate);
            editor.putFloat("won_rate",wonRate);
            editor.apply();
            Log.i(TAG,"onActivityResult:save to sp");

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if(item.getItemId()==R.id.menu_setting){
            openconfig();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void run() {
        Log.i(TAG,"run:run.......");

        try {
            Thread.sleep(3000);
        }catch(InterruptedException e){
            e.printStackTrace();
        }

        Log.i(TAG,"run:run2");
//        URL url = null;
//        try{
//            url = new URL("https://www.usd-cny.com/bankofchina.htm");
//            HttpURLConnection http = (HttpURLConnection) url.openConnection();
//            InputStream in = http.getInputStream();
//
//            String html = inputStream2String(in);
//            Log.i(TAG,"run:html="+html);
//
//        }catch (MalformedURLException e){
//            e.printStackTrace();
//        }catch (IOException e){
//            e.printStackTrace();
//        }

        Bundle bdl = new Bundle();
        //使用JSOUP获取页面元素
        try {
            Document doc = Jsoup.connect("https://www.usd-cny.com/bankofchina.htm").get();
            Log.i(TAG,"run:title="+doc.title());
            Element table = doc.getElementsByTag("table").first();
            Log.i(TAG,"tun:table="+table);
            Elements trs = table.getElementsByTag("tr");
            trs.remove(0);
            Elements ps = doc.getElementsByTag("p");
            Element p = ps.get(0);
            bdl.putString("time",p.text());
            for(Element tr : trs){
                Elements tds = tr.getElementsByTag("td");
                if(tds.size()>0){
                    Element td1 = tds.first();
                    Element td2 = tds.last();

                    String str1 = td1.text();
                    String str2 = td2.text();
                    Log.i(TAG,"run :"+td1.text()+"-->"+td2.text());
                    if("欧元".equals(str1)){
                        bdl.putFloat("web_euro",100f/Float.parseFloat(str2));
                    }else if("美元".equals(str1)){
                        bdl.putFloat("web_dollar",100f/Float.parseFloat(str2));
                    }else if("韩元".equals(str1)){
                        bdl.putFloat("web_won",100f/Float.parseFloat(str2));
                    }
                }
            }

//            Element td1 = doc.selectFirst("body > section > div > div > article > table > tbody > tr:nth-child(27) > td.bz > a");
//            Log.i(TAG,"run:td1="+td1.text());

//            Element td1 = table.selectFirst("tr:nth-child(27) > td:nth-child(6)");
//            Log.i(TAG,"run:td1="+td1.text());

//            Elements tds = table.getElementsByTag("td");
//            for(int i = 0;i<tds.size();i+=8){
//                Element td1 = tds.get(i);
//                Element td2 = tds.get(i+5);
//                String str1 = td1.text();
//                String str2 = td2.text();
//                Log.i(TAG,"run:"+str1+"==>"+str2);
//
//                float v = 100f/Float.paresFloat(str2);
//            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        Message msg = handler.obtainMessage(7,bdl);
        handler.sendMessage(msg);
    }
    private String inputStream2String(InputStream inputStream)
            throws IOException{
        final int bufferSize = 1024;
        final char[] buffer = new char[bufferSize];
        final StringBuilder out = new StringBuilder();
        Reader in = new InputStreamReader(inputStream,"gb2312");
        while (true){
            int rsz = in.read(buffer,0,buffer.length);
            if(rsz < 0)
                break;
            out.append(buffer,0,rsz);
        }
        return out.toString();
    }
}